# -*- coding: utf-8 -*-
'''
@author: lowzoom
'''
from __future__ import print_function
from collections import OrderedDict
import cfg
import main
import os
import re
import shutil

rna_cfg = OrderedDict()

# 配置文件名
RNA_FILENAME = 'rna.ini'

# 键
GENERAL = ''
FULL_SCREEN = 'FULLSCREEN'
LOCALE = 'LOCALE'
USE_LANGUAGE_SELECT = 'USE_LANGUAGE_SELECT'
DEFAULT_LANGUAGE = 'DEFAULT_LANGUAGE'

# 匹配无用内容的正则
comment_ptn = re.compile(r'(^[;#].*\r?\n)|' # 整行注释
												r'(^//.*\r?\n)|'
												r'(\s+[;#].*$)|' # 行中注释
												r'(\s+//.*$)|'
												r'(^\s*\r?\n)') # 空行

# 提取键值的正则
section_ptn = re.compile(r'^\[(.*)\]$')
separator_ptn = re.compile(r'\s*[:=]\s*')

def load():
	'''
	读取 rna.ini 文件
	'''
	assert os.path.exists(cfg.pref[cfg.GAME_PATH])

	if not os.path.isfile(cfg.pref[cfg.RNA_PATH]):
		shutil.copy(os.path.join(main.base_path, 'data', RNA_FILENAME), cfg.pref[cfg.GAME_PATH])

	with open(cfg.pref[cfg.RNA_PATH], 'r') as rna_file:
		# 先去注释, 再去空行 和 两边空白
		rna_content = [line.strip() for line in [comment_ptn.sub('', line) for line in rna_file] if line]

	# 将配置读进内存
	rna_cfg.clear()
	current_section = rna_cfg.setdefault(GENERAL, OrderedDict())
	for line in rna_content:
		matcher = section_ptn.match(line)
		if matcher:
			current_section = rna_cfg.setdefault(matcher.group(1), OrderedDict())
		else:
			pair = separator_ptn.split(line)
			assert len(pair) == 2
			current_section[pair[0]] = pair[1]

def save():
	'''
	保存 rna.ini 文件
	'''
	# 备份原配置
	rna_bak_path = '.'.join((cfg.pref[cfg.RNA_PATH], main.__author__))
	if os.path.isfile(cfg.pref[cfg.RNA_PATH]) and not os.path.isfile(rna_bak_path):
		shutil.copyfile(cfg.pref[cfg.RNA_PATH], rna_bak_path)

	with open(cfg.pref[cfg.RNA_PATH], 'w') as rna_file:
		for sctn, pair in rna_cfg.iteritems():
			if pair:
				rna_file.write('[{s}]\n'.format(s=sctn))
				for key, val in pair.iteritems():
					rna_file.write('{k} = {v}\n'.format(k=key, v=val))

def is_windowed():
	return int(rna_cfg[GENERAL][FULL_SCREEN]) < 0

def set_windowed(windowed):
	rna_cfg[GENERAL][FULL_SCREEN] = '-1' if windowed else '1'

def is_skip_language_select():
	return rna_cfg[LOCALE][USE_LANGUAGE_SELECT] == '0'

def set_skip_language_select(skip, default_lang='eng,us'):
	rna_cfg[LOCALE][USE_LANGUAGE_SELECT] = '0' if skip else '1'
	rna_cfg[LOCALE][DEFAULT_LANGUAGE] = default_lang


if __name__ == '__main__':
	main.base_path = os.path.dirname(main.base_path)
	
	cfg.set_game_path(r'E:\Game\FIFA.12\FIFA.12.RUS_EPIDEMZ.NET\Game')
#	cfg.set_game_path(r'C:\Users\lowzoom\Desktop\fuck\1')
	
	load()
	print('\n'.join((
		'windowed: {w}',
		'skip_lang: {s}')).format(
			w=is_windowed(),
			s=is_skip_language_select()))

	set_windowed(not is_windowed())
	set_skip_language_select(not is_skip_language_select())
	save()
